package com.chookss.home.audit.shop;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.ShopEvent;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.RoundCornerImageView;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class ShopNormalActivity extends BaseAct {
//我的正常可选物品

    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private ShopChoiceTypeAdapter adapter;
    private ArrayList<ReimbursementDetailEntity.GoodsInfosBean> list = new ArrayList<>();
    private ArrayList<ReimbursementDetailEntity.GoodsInfosBean> oldList = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private ArrayList<ReimbursementDetailEntity.GoodsInfosBean> selectlist = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_choice);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_title_txt.setText("我的物品");
        common_right_txt.setText("确定");
        common_right_txt.setTextColor(getResources().getColor(R.color.main_color));
        common_right_txt.setVisibility(View.VISIBLE);
        oldList.clear();
        oldList.addAll((List<ReimbursementDetailEntity.GoodsInfosBean>) getIntent().getSerializableExtra("data"));
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 12f), getResources().getColor(R.color.main_bg)));
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new ShopChoiceTypeAdapter(R.layout.item_shop_choice, this, list);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("暂无物品");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("isApp",  "1");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<ReimbursementDetailEntity.GoodsInfosBean>>>() {
        }.getType(), null, Urls.selectGoodsPageList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ReimbursementDetailEntity.GoodsInfosBean>>() {
            @Override
            public void onSuccess(List<ReimbursementDetailEntity.GoodsInfosBean> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    int old = list.size();
                    for (int i = 0; i < data.size(); i++) {
                        if ("1".equals(data.get(i).getAuditCd())) {
                            list.add(data.get(i));
                            for (int j = 0; j <oldList.size() ; j++) {
                                 if(oldList.get(j).getGoodsCode().equals(data.get(i).getGoodsCode())){
                                     list.get(list.size()-1).setChecked(true);
                                 }
                            }
                        }
                    }
                    adapter.notifyItemRangeChanged(old, list.size() - old);

                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class ShopChoiceTypeAdapter extends BaseQuickAdapter<ReimbursementDetailEntity.GoodsInfosBean, BaseViewHolderEx> {
        private Activity context;

        public ShopChoiceTypeAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<ReimbursementDetailEntity.GoodsInfosBean> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ReimbursementDetailEntity.GoodsInfosBean entity) {
            RelativeLayout rlType = helper.getView(R.id.rlType);
            RelativeLayout rlStatus = helper.getView(R.id.rlStatus);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvType = helper.getView(R.id.tvType);
            TextView tvInit = helper.getView(R.id.tvInit);
            RoundCornerImageView ivImg = helper.getView(R.id.ivImg);
            ImageView ivStatus = helper.getView(R.id.ivStatus);
            rlStatus.setVisibility(View.VISIBLE);
            tvType.setVisibility(View.GONE);
            tvInit.setText("所属人:" + entity.getOwnerEmployeeName() + "   所属项目组:" + entity.getGroupName());
            GlideUtils.load(context, entity.getImageUrl(), ivImg, R.drawable.default_news);
            String title = entity.getGoodsName() + " <font color='#999999'>" + entity.getGoodsCode() + "</font> " + ClearMoreZeroUtil.subZeroAndDot(entity.getAmt()) + "元";
            tvTitle.setText(Html.fromHtml(title));
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivStatus.getLayoutParams();
            if (entity.isChecked()) {
                params.height = Utils.dip2px(context, 24);
                params.width = Utils.dip2px(context, 24);
                ivStatus.setBackgroundResource(R.drawable.icon_fx_select);
            } else {
                params.height = Utils.dip2px(context, 14);
                params.width = Utils.dip2px(context, 14);
                ivStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
            }
            ivStatus.setLayoutParams(params);
            rlStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (entity.isChecked()) {
                        entity.setChecked(false);
                    } else {
                        entity.setChecked(true);
                    }
                    adapter.notifyItemChanged(helper.getItemPosition());
                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(context, ShopDetailActivity.class);
                    intent.putExtra("goodsCode", entity.getGoodsCode());
                    context.startActivity(intent);
                }
            });
        }
    }
    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.common_right_txt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                selectlist.clear();
                for (int i = 0; i < list.size(); i++) {
                    if(list.get(i).isChecked()){
                        selectlist.add(list.get(i));
                    }
                }
                EventBus.getDefault().post(new ShopEvent(selectlist));
                finish();
                break;
        }
    }
}
